// backend/server.js
const express = require('express');
const cors = require('cors');
const path = require('path');

// 导入路由
const metadataDrivenRouter = require('./api/metadata-driven');

const app = express();
const PORT = process.env.PORT || 3001;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 静态文件服务（如果需要）
app.use(express.static(path.join(__dirname, '../public')));

// API路由
app.use('/api/metadata-driven', metadataDrivenRouter);

// 健康检查端点
app.get('/api/health', (req, res) => {
  res.json({ status: 'OK', timestamp: new Date().toISOString() });
});

// 根路径
app.get('/', (req, res) => {
  res.json({
    message: '元数据驱动API服务已启动',
    version: '1.0.0',
    endpoints: [
      'GET /api/metadata-driven/data-sources',
      'GET /api/metadata-driven/data-sources/:id',
      'GET /api/metadata-driven/data-sources/:id/data',
      'POST /api/metadata-driven/data-sources/:id/data',
      'PUT /api/metadata-driven/data-sources/:id/data/:recordId',
      'DELETE /api/metadata-driven/data-sources/:id/data/:recordId'
    ]
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    code: 500,
    message: '服务器内部错误'
  });
});

// 404处理
app.use((req, res) => {
  res.status(404).json({
    code: 404,
    message: '接口不存在'
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`元数据驱动API服务器已启动，端口: ${PORT}`);
  console.log(`访问 http://localhost:${PORT} 查看API信息`);
});

// 添加CORS中间件
app.use(cors({
  origin: 'http://localhost:3000', // 允许前端地址
  credentials: true
}));


module.exports = app;
